<template>
  <div class="top-head">
    <div class="banxin flex">
      <div class="welcom">欢迎来到叩丁严选</div>
      <div class="right flex">
        <ul class="flex">
          <li>
            <img :src="userInfo.headImg" alt="" />
            <span>用户名：</span>
            <span>{{ userInfo.nickName }}</span>
          </li>
          <li>
            <span>我的鸡腿： </span>
            <span>{{ userInfo.coin }}</span>
          </li>
          <li>
            <span>获取鸡腿</span>
          </li>
          <li>
            <span>叩丁狼官网</span>
          </li>
        </ul>
        <div
          class="btn"
          @click="$store.commit('xgshowlogin', true)"
          v-show="!islogin"
        >
          登录
        </div>
        <div class="btn" v-show="islogin">
          <img src="" alt="" />
          <span>购物车</span>
          <span class="ttal">{{ cartTotal }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getuserApi, WeixinLoginApi } from "../../http/api";

//静态图片要获取动态图片需要导入
import headImg from "../../assets/images/userImg.png";
import { toast } from "../../utils/toast";
export default {
  data() {
    return {
      userInfo: {
        headImg,
        nickName: "",
        coin: "",
      },
      cartTotal: 0,
      islogin: false,
    };
  },
  created() {
    // console.log(this.$route.query);
    this.weixinlogin();
    this.getuser();
  },
  methods: {
    weixinlogin() {
      const code = this.$route.query.code;
      // console.log(code);
      WeixinLoginApi(code).then((res) => {
        // console.log(res);
        if (res.code === 0) {
          localStorage.setItem("x-auth-token", res["x-auth-token"]);
          toast("登录成功!!!", "success");
          this.getuser();
        }
      });
    },
    async getuser() {
      //判断是否登录,有没有token
      const token = localStorage.getItem("x-auth-token");
      if (!token) return;
      this.islogin = true;
      const res = await getuserApi();
      console.log(res);
      if (res.code === 0) {
        //给它赋值
        this.userInfo = res.data.userInfo;
        this.cartTotal = res.data.cartTotal;
      }
    },
  },
  watch: {
    "$route.query": {
      handler() {
        this.weixinlogin();
      },
    },
  },
};
</script>
 
<style lang = "less" scoped>
.top-head {
  color: #fff;
  font-size: 14px;
  height: 40px;
  line-height: 40px;
  background: #242b39;
  .banxin {
    justify-content: space-between;
  }
  .right {
    ul {
      li {
        cursor: pointer;
        margin-right: 20px;
        img {
          width: 26px;
          height: 26px;
          vertical-align: middle;
          margin-right: 15px;
          border-radius: 50%;
        }
      }
    }
    .btn {
      cursor: pointer;
      width: 124px;
      text-align: center;
      background: #0a328e;
    }
  }
}
</style>